package com.interview.score.controller;

import com.interview.score.common.ExameeState;
import com.interview.score.common.Result;
import com.interview.score.common.ResultMessage;
import com.interview.score.common.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Stream;

@RestController
@RequestMapping("/interviewProcess")
public class InterviewProcessController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Environment env;

    @PostMapping("getExamRoomId")
    public String getExamRoomId() {
        String examRoomId = (String) redisTemplate.opsForValue().get(env.getProperty("ExamRoomIdKey"));
        return examRoomId;
    }

    @PostMapping("getInterviewProcessData")
    public Result getInterviewProcessData() {
        String examRoomId = getExamRoomId();
        /**
         * 获取面试人员序列
         */
        //1.获取待考考生序列
        String exameeSequenceKey = env.getProperty("ExameeSequenceKey");
        List exameeSequence = redisTemplate.opsForList().range(exameeSequenceKey+"-"+examRoomId, 0, -1);
        HashMap<Integer, Integer> exameeSequence_State = new HashMap<>();
        for (int i = 0; i < exameeSequence.size(); i++) {
            if (i==0){

                exameeSequence_State.put((Integer) exameeSequence.get(i), ExameeState.InterviewIng);
            }else {
                exameeSequence_State.put((Integer)exameeSequence.get(i), ExameeState.UnFinished);
            }
        }
        //2.获取缺考考生序列
        Set absentSequence = redisTemplate.opsForSet().members(env.getProperty("AbsentSequenceKey")+"-"+examRoomId);
        HashMap<Integer, Integer> absentSequence_State = new HashMap<>();
        for (Object o : absentSequence) {
            absentSequence_State.put((Integer)o, ExameeState.Absent);
        }
        //3.获取完成考试人员序列
        List finishedExameeSequence = redisTemplate.opsForList().range(env.getProperty("FinishedExameeSequenceKey") + "-" + examRoomId, 0, -1);
        HashMap<Integer, Integer> finishedExameeSequence_State = new HashMap<>();
        for (Object o : finishedExameeSequence) {
            finishedExameeSequence_State.put((Integer)o, ExameeState.Finished);
        }
        //4、合并hash
        Map<Integer, Integer> resultMap = new TreeMap<>(){{
            putAll(exameeSequence_State);
            putAll(absentSequence_State);
            putAll(finishedExameeSequence_State);
        }};
        //5.排序
        return new Result(true, StatusCode.OK, ResultMessage.OPERATION_SUCCESS,resultMap);
    }
}
